<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>二级关联</title>
		<style type="text/css">
			ul{padding: 0;margin: 0;}
			li{list-style: none;}
			.box{width: 400px;height: 100px;background: #fff;border-radius: 10px;position: fixed;top: 50%;left: 50%;margin-left: -200px;margin-top: -50px;display: none;border: 1px solid brown;z-index: 2;}
			.box li{float: left;width: 100px;height: 30px;line-height: 30px;text-align: center;}
			#mask{width: 100%;height: 100%;position: fixed;top: 0px;left: 0px;background: rgba(0,0,0,0.4);display: none;z-index: 1;}
		</style>
	</head>
	<body>
		<div id="cityName">北京</div>
		<button id="otherBtn">其他城市</button>
		<div id="province" class="box"><ul></ul></div>
		<div id="city" class="box"><ul></ul></div>
		<div id="mask"></div>
		
		<script type="text/javascript">
			//定义数据
			var cityData = [
				{pname:"河北",citys:["石家庄","保定"]},
				/*{pname:"河北",citys:[{cname:"石家庄",ages:["",""]}"保定"]},三级关联*/
				{pname:"山东",citys:["济南","青岛"]},
				{pname:"山西",citys:["太原","大同"]}
			];
			var data = {};
			function $(ele){
				return document.querySelectorAll(ele);
			}
			/*
			 * 第一次需要动态生成，以后避免再次生成
			 * 1、生成省的列表
			 * 2、根据选择的省，遍历省下的城市
			 * 3、点城市，获取值
			 * 
			 * */
			
			var otherBtn = $("#otherBtn")[0],
				cityName = $("#cityName")[0],
				plist = $("#province ul")[0],
				clist = $("#city ul")[0],
				province = $("#province")[0],
				city = $("#city")[0],
				mask = $("#mask")[0],
				oct,
				opr;
				
			otherBtn.onclick=function(){
				if(!opr){//判断opr里面是否有li，来决定是否需要遍历数组
					cityData.forEach(function(item,index){
						plist.innerHTML+="<li>"+item.pname+"</li>";
					})
					opr=$("#province li");
				}
				province.style.display="block";
				mask.style.display="block";
			}
			plist.onclick=function(e){
				if(e.target.tagName=="LI"){
					var pname = e.target.innerHTML;
					for(var i=0;i<cityData.length;i++){
						//判断点击元素的内容是否与数组中的pname一致，如果相等，即可取到对应的所有城市
						if(pname==cityData[i].pname){
							clist.innerHTML="";
							//遍历里面的citys
							cityData[i].citys.forEach(function(item){
								clist.innerHTML+="<li>"+item+"</li>";
							})
							city.style.display="block";
							province.style.display="none";
							oct=$("#city li");
						}
					}
				}
			}
			clist.onclick=function(e){
				
				if(e.target.tagName=="LI"){
					//提取数据
					data.city=e.target.innerHTML;
					mask.style.display="none";
					city.style.display="none";
					cityName.innerHTML=e.target.innerHTML;
				}
			}
			//点击遮罩的时候，框隐藏
			mask.onclick=function(){
				this.style.display="none";
				province.style.display="none";
				city.style.display="none";
			}
		</script>
	</body>
</html>
